package com.cx.config;

import com.cx.exception.AccessDeniedHandlerImpl;
import com.cx.exception.AuthenticationEntryPointImpl;
import com.cx.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启权限认证
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭csrf
                .csrf().disable()
                // 不通过Session获取SecurityContext对象
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口允许匿名访问,匿名访问表示未认证是可以访问放行请求，认证了反而不能访问
                .antMatchers("/user/login","/user/register").anonymous()
                .antMatchers("/doc.html", "/webjars/**", "/v2/api-docs", "/swagger-resources/**","/customer/**").permitAll()
                // 除了上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();


        // 将我们自定义的过滤器放在UsernamePasswordAuthenticationFilter过滤器之前，用于检测是否通过认证
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);


        // 配置异常处理器
        http.exceptionHandling().
                // 配置认证失败处理器
                        authenticationEntryPoint(authenticationEntryPoint).
                // 配置权限失败处理器
                        accessDeniedHandler(accessDeniedHandler);

        // springSecurity开启允许跨域
        http.cors();

    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    // 用于对密码进行编码的服务接口
    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }
}
